package com.example.lottery.util;

import org.apache.commons.beanutils.BeanUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.ReflectionUtils;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.util.*;

public final class ObjectUtils {

    private static final Logger logger = LoggerFactory.getLogger(ObjectUtils.class);

    private ObjectUtils() {
    }

    public static <T> T build(Class<T> clazz, Object source) {
        if (null == clazz || null == source) return null;

        try {
            T target = clazz.newInstance();
            return build(source, target);
        } catch (Exception e) {
            logger.error("Object构造失败！", e);
        }
        return null;
    }

    public static <T, V> T buildMap(Class<T> clazz, Map<String, V> source) {
        if (null == clazz || null == source) return null;

        try {
            T target = clazz.newInstance();
            return buildMap(source, target);
        } catch (Exception e) {
            logger.error("Object构造失败！", e);
        }
        return null;
    }

    public static <T, V> List<T> buildBatchMap(Class<T> clazz, List<Map<String, V>> source) {
        if (null == clazz || null == source) return null;

        List<T> target = new ArrayList<T>();
        for (Map<String, V> s : source) {
            target.add(buildMap(clazz, s));
        }
        return target;
    }

    public static <T> T build(Object source, T target) {
        if (null == source || null == target) return null;

        try {
            Map<String, Field> sourceMap = getAllFields(source.getClass());
            Map<String, Field> targetMap = getAllFields(target.getClass());
            for (Map.Entry<String, Field> s : sourceMap.entrySet()) {
                for (Map.Entry<String, Field> t : targetMap.entrySet()) {
                    if (StringUtils.equals(s.getKey(), t.getKey())) {
                        s.getValue().setAccessible(true);
                        t.getValue().setAccessible(true);
                        t.getValue().set(target, s.getValue().get(source));
                    }
                }
            }
            return target;
        } catch (Exception e) {
            logger.error("Object构造失败！", e);
        }
        return null;
    }

    public static <T, V> T buildMap(Map<String, V> source, T target) {
        if (null == source || null == target) return null;

        try {
            Map<String, Field> targetMap = getAllFields(target.getClass());
            for (Map.Entry<String, V> s : source.entrySet()) {
                for (Map.Entry<String, Field> t : targetMap.entrySet()) {
                    if ((StringUtils.equals(s.getKey(), t.getKey())
                            || StringUtils.equals(StringUtils.nderline2Camel(s.getKey()), t.getKey()))
                            && s.getValue().getClass() == t.getValue().getType()) {
                        t.getValue().setAccessible(true);
                        t.getValue().set(target, s.getValue());
                    }
                }
            }
            return target;
        } catch (Exception e) {
            logger.error("Object构造失败！", e);
        }
        return null;
    }

    /**
     * @param entityClass
     * @param objects
     * @return
     */
    public static <T> List<T> buildBatch(Class<T> entityClass, List objects) {
        List<T> list = new ArrayList<T>();
        for (Object object : objects) {
            T t = build(entityClass, object);
            if (null != t) {
                list.add(t);
            }
        }

        return list;
    }

    public static Map<String, Field> getAllFields(Class clazz) {
        final Map<String, Field> fieldMap = new LinkedHashMap<>();
        iterateAllFields(clazz, f -> fieldMap.put(f.getName(), f));
        return fieldMap;
    }

    public static Map<String, Field> getDeclaredFields(Class clazz) {
        final Map<String, Field> fieldMap = new LinkedHashMap<>();
        iterateDeclaredFields(clazz, f -> fieldMap.put(f.getName(), f));
        return fieldMap;
    }

    public static void iterateAllFields(Class clazz, FiledFilter filter) {
        if (null == clazz || null == filter) {
            return;
        }

        do {
            iterateDeclaredFields(clazz, filter);
        } while (null != clazz.getSuperclass()
                && Object.class != (clazz = clazz.getSuperclass()));
    }

    public static void iterateDeclaredFields(Class clazz, FiledFilter filter) {
        for (Field f : clazz.getDeclaredFields()) {
            filter.doItem(f);
        }
    }

    public static boolean equals(Object obj1, Object obj2) {
        if (null == obj1 && null == obj2) {
            return true;
        }
        if (null == obj1 || null == obj2) {
            return false;
        }
        return obj1 == obj2 || obj1.equals(obj2);
    }

    public interface FiledFilter<T extends Collection> {
        void doItem(Field field);
    }

    /**
     * @description: 比较字段值
     * @author bin sun
     * @return true 相同;false 不同
     * @date 2023/10/9 13:58
     */
    public static boolean compareFileds(Object obj1,Object obj2){
        boolean result = true;
        Field[] fields1 = obj1.getClass().getDeclaredFields();
        Field[] fields2 = obj2.getClass().getDeclaredFields();
        try {
            for (Field field1 : fields1) {
                //设置允许访问私有变量
                ReflectionUtils.makeAccessible(field1);
                if(field1.get(obj1) == null){
                    continue;
                }
                if(!result){
                    break;
                }
                for (Field field2 : fields2) {
                    ReflectionUtils.makeAccessible(field2);
                    if(field2.get(obj2) == null){
                        continue;
                    }
                    if(field1.getName().equals(field2.getName())){
                        if(!field1.get(obj1).equals(field2.get(obj2))){
                            result = false;
                            break;
                        }
                    }
                }
            }
        }catch (Exception ignored){
        }
        return result;
    }

    /**
     * @description: 对象中字段去除空格
     * @author bin sun
     * @date 2024/1/12 15:57
     */
    public static synchronized void objectToTrim(Object object) {
        Map<String,String> map = new HashMap<>();
        Field[] fields = getAllFields(object);
        for (Field field : fields){
            String type = field.getType().getCanonicalName();
            if ("java.lang.String".equals(type)){
                ReflectionUtils.makeAccessible(field);
                Object getObject = null;

                try {
                    getObject = field.get(object);
                } catch (IllegalAccessException ignored) {
                    logger.error("Object构造失败！ 方法名：objectToTrim", ignored);
                }

                if (getObject != null) {
                    String trim = getObject.toString().trim();
                    map.put(field.getName(), trim);
                }
            }
        }

        for (Field field : fields) {
            if (map.get(field.getName()) != null){
                String trimValue = map.get(field.getName());
                ReflectionUtils.makeAccessible(field);
                try {
                    BeanUtils.setProperty(object,field.getName(),trimValue);
                } catch (InvocationTargetException | IllegalAccessException ignored) {
                    logger.error("Object构造失败！ 方法名：objectToTrim", ignored);
                }
            }
        }
    }

    /**
     * 获取子类和父类所有字段信息
     */
    private static Field[] getAllFields(Object object) {
        Class clazz = object.getClass();

        List<Field[]> fieldsList = new ArrayList<>();
        while (clazz != null) {
            Field[] declaredFields = clazz.getDeclaredFields();
            fieldsList.add(declaredFields);

            clazz = clazz.getSuperclass();
        }

        List<Field> allFields = new ArrayList<>();
        for (Field[] fields : fieldsList) {
            allFields.addAll(Arrays.asList(fields));
        }

        return allFields.toArray(new Field[0]);
    }
}
